package com.trkj.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.trkj.base.BaseActivity;
import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.newwork.HttpRequest;
import com.trkj.base.newwork.ProgressBarPostDataFromRemote;
import com.trkj.base.utils.UserService;
import com.trkj.taoruiyun.R;

import java.text.MessageFormat;

/**
 * Created by LiZanhong on 2015/06/21.
 */
public class UpdatePasswordActivity extends BaseActivity {
    @ViewInject(R.id.old_password)
    private EditText oldPassword;

    @ViewInject(R.id.password)
    private EditText newPassword1;

    @ViewInject(R.id.password2)
    private EditText newPassword2;

    private HttpRequest httpRequest;
    private UserService userService;

    public static final String ACTION = "com.trkj.usercenter.UpdatePasswordActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_updatepassword);

        ViewUtils.inject(this);
        httpRequest = new HttpRequest();
        userService = UserService.getInstance(this);
    }


    @Override
    protected String getCustomerTitle() {
        return "修改密码";
    }

    /**
     * 密码
     * @param v
     */
    public void updatePassword(View v){
        String strNewPassword1 = newPassword1.getText().toString();
        if(TextUtils.isEmpty(strNewPassword1)){
            toast("密码不能为空");
            return;
        }

        if(!strNewPassword1.equals(newPassword2.getText().toString())){
            toast("两次密码输入不一致");
            return;
        }

        if(!userService.getPassword().equals(oldPassword.getText().toString())){
            toast("原密码输入错误");
            return;
        }

        ProgressBarPostDataFromRemote dataFromRemote =
                new ProgressBarPostDataFromRemote(this);
        dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
            @Override
            public void onResponseResult(String result) {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject.getBoolean("success")){
                    toast("密码修改成功，请重新登录");
                    Intent intent = new Intent(LoginActivity.ACTION);
                    finish();
                    startActivity(intent);
                }else{
                    toast("密码修改失败");
                }
            }
        });

        int uid = userService.parseUser().userId;
        String url = MessageFormat.format(Constants.ApiUrl.UPDATE_PASSWORD, uid);
        dataFromRemote.execute(url, "password=" + newPassword1.getText().toString());
    }
}
